package cn.unknownerror.ueteam.listener;

import cn.unknownerror.ueteam.gui.AbstractButton;
import cn.unknownerror.ueteam.gui.AbstractFrame;
import cn.unknownerror.ueteam.gui.FrameManager;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.inventory.InventoryClickEvent;
import org.bukkit.event.inventory.InventoryType;

public class FrameListener implements Listener {

    private FrameManager manager;

    public FrameListener(FrameManager manager){
        this.manager=manager;
    }

    @EventHandler
    public void onClick(InventoryClickEvent event){
        if(!(event.getWhoClicked() instanceof Player)){
            return;
        }
        for (AbstractFrame frame:manager.getFrames()){
            if(event.getSlot()<0||event.getClickedInventory()==null
                    ||event.getClickedInventory().getType()!=InventoryType.CHEST){
                return;
            }
            if(!frame.isFrame(event.getView().getTitle())){
                continue;
            }
            event.setCancelled(true);
            AbstractButton button=frame.getButton(event.getSlot());
            if(button==null){
                return;
            }
            button.onClick((Player)event.getWhoClicked());
            return;
        }
    }
}
